package com.homedo.odin.solution.service.bizservice.pc;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.homedo.core.common.base.dto.Meta;
import com.homedo.core.common.exception.BizException;
import com.homedo.core.common.util.BeanUtils;
import com.homedo.core.common.util.CommonDataUtil;
import com.homedo.core.common.util.NumberHelper;
import com.homedo.core.common.util.ParamCheckUtil;
import com.homedo.odin.solution.contract.pc.BrandFirmSolutionResp;
import com.homedo.odin.solution.contract.pc.SSolutionDetailResp;
import com.homedo.odin.solution.contract.pc.SkuListResp;
import com.homedo.odin.solution.contract.pc.SolutionAddPcReq;
import com.homedo.odin.solution.contract.pc.SolutionEditPcReq;
import com.homedo.odin.solution.contract.pc.SolutionResp;
import com.homedo.odin.solution.contract.pc.USolutionDetailResp;
import com.homedo.odin.solution.contract.pc.UserDownloadAuthResp;
import com.homedo.odin.solution.contract.pc.UserSolutionDetailResp;
import com.homedo.odin.solution.contract.pc.UserSolutionResp;
import com.homedo.odin.solution.contract.wap.SolutionListResp;
import com.homedo.odin.solution.enumcode.basic.BusinessTypeEnum;
import com.homedo.odin.solution.enumcode.basic.ChargeEnum;
import com.homedo.odin.solution.enumcode.basic.CommonTypeDataEnum;
import com.homedo.odin.solution.enumcode.basic.DeleteEnum;
import com.homedo.odin.solution.enumcode.basic.DownloadCollectEnum;
import com.homedo.odin.solution.enumcode.basic.DownloadEnum;
import com.homedo.odin.solution.enumcode.basic.ErrorCodeEnum;
import com.homedo.odin.solution.enumcode.basic.FromTypeEnum;
import com.homedo.odin.solution.enumcode.other.MemberLevelEnum;
import com.homedo.odin.solution.enumcode.solution.SolutionStateEnum;
import com.homedo.odin.solution.enumcode.solution.SolutionTypeEnum;
import com.homedo.odin.solution.enumcode.user.PayStateEnum;
import com.homedo.odin.solution.model.dto.AttachmentInfoResponseBean;
import com.homedo.odin.solution.model.dto.BrandFirmSolutionResponseBean;
import com.homedo.odin.solution.model.dto.PageBean;
import com.homedo.odin.solution.model.dto.SkuListResponseBean;
import com.homedo.odin.solution.model.dto.SolutionListResponseBean;
import com.homedo.odin.solution.model.dto.SolutionResponseBean;
import com.homedo.odin.solution.model.dto.UserIncomeDetailResponseBean;
import com.homedo.odin.solution.model.dto.UserSolutionBean;
import com.homedo.odin.solution.model.dto.search.SearchResponseBean;
import com.homedo.odin.solution.model.dto.search.SearchSolution;
import com.homedo.odin.solution.model.entity.Attachment;
import com.homedo.odin.solution.model.entity.BrandFirm;
import com.homedo.odin.solution.model.entity.BrandOwner;
import com.homedo.odin.solution.model.entity.Solution;
import com.homedo.odin.solution.model.entity.SolutionSku;
import com.homedo.odin.solution.model.entity.UserPayOrder;
import com.homedo.odin.solution.model.entity.UserSolution;
import com.homedo.odin.solution.service.AttachmentServiceImpl;
import com.homedo.odin.solution.service.BrandFirmServiceImpl;
import com.homedo.odin.solution.service.BrandOwnerServiceImpl;
import com.homedo.odin.solution.service.CommonTypeDataServiceImpl;
import com.homedo.odin.solution.service.HebiOrderServiceImpl;
import com.homedo.odin.solution.service.SmsServiceImpl;
import com.homedo.odin.solution.service.SolutionServiceImpl;
import com.homedo.odin.solution.service.SolutionSkuServiceImpl;
import com.homedo.odin.solution.service.UserPayOrderServiceImpl;
import com.homedo.odin.solution.service.UserSolutionServiceImpl;
import com.homedo.odin.solution.service.common.HomedoService;
import com.homedo.odin.solution.service.common.SearchService;
import com.homedo.odin.solution.util.SolutionBeansConvertUtil;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: zhaoxudong
 * @date: 2018/3/27 17:36
 * @Description:
 */
@Service
public class SolutionsBizService {

    @Autowired
    SolutionServiceImpl solutionService;
    @Autowired
    UserSolutionServiceImpl userSolutionService;
    @Autowired
    BrandOwnerServiceImpl brandOwnerService;
    @Autowired
    BrandFirmServiceImpl brandFirmService;
    @Autowired
    SearchService searchService;
    @Autowired
    UserPayOrderServiceImpl userPayOrderService;
    @Autowired
    HebiOrderServiceImpl hebiOrderService;
    @Autowired
    AttachmentServiceImpl attachmentService;
    @Autowired
    SmsServiceImpl smsServiceImpl;
    @Autowired
    SolutionSkuServiceImpl solutionSkuService;
    @Autowired
    HomedoService homedoService;
    @Autowired
    CommonTypeDataServiceImpl commonTypeDataService;

    /**
     * 查询方案信息列表
     *
     * @param solutionType 方案类型1:系统方案 2:品牌方案
     * @param uid 当前登录用户
     * @param brandId 品牌id
     * @param sysAttr 系统属性(一级系统属性)
     * @param buildingType 建筑业态
     * @param isMy 我的(0:否 1:是)
     * @param expType 曝光类型 1：精品 2：普通
     * @param shelveTimeSort 发布日期(0:升序 1:降序)
     * @param createTimeSort 创建日期(0:升序 1:降序)
     * @param downloadCountSort 下载数量(0:升序 1:降序)
     * @param viewCountSort 浏览数量(0:升序 1:降序)
     * @param commentCountSort 评论数量(0:升序 1:降序)
     * @param pageNum 当前页码
     * @param pageSize 每页记录数
     */
    public SolutionResp list(Integer solutionType, Integer uid, Integer brandId, Integer sysAttr, Integer buildingType,
            Integer isMy, Integer expType, Integer shelveTimeSort, Integer createTimeSort,
            Integer downloadCountSort, Integer viewCountSort, Integer commentCountSort, Integer pageNum,
            Integer pageSize) {
        ParamCheckUtil.checkPageParam(pageNum, pageSize);
        PageInfo<Solution> queryResult = null;
        PageInfo<Solution> hotResult = null;
        if (isMy != null && 1 == isMy.intValue()) {
            PageHelper.startPage(pageNum, pageSize);
            queryResult = new PageInfo<>(solutionService.queryMySolutionForPc(solutionType, sysAttr, buildingType,
                    shelveTimeSort, createTimeSort, downloadCountSort, viewCountSort, commentCountSort,
                    SolutionStateEnum
                            .SHELVE.getDbValue(),
                    expType, uid, brandId
            ));
            PageHelper.startPage(1, 4);
            hotResult = new PageInfo<>(solutionService.queryMySolutionForPc(null, null, null,
                    null, 1, 1, 1, 1, SolutionStateEnum
                            .SHELVE.getDbValue(),
                    null, null, null
            ));
        } else {
            PageHelper.startPage(pageNum, pageSize);
            queryResult = new PageInfo<>(solutionService.querySolutionForPc(solutionType, sysAttr, buildingType,
                    shelveTimeSort, createTimeSort, downloadCountSort, viewCountSort, commentCountSort,
                    SolutionStateEnum.SHELVE
                            .getDbValue(),
                    expType, uid, brandId
            ));
            PageHelper.startPage(1, 4);
            hotResult = new PageInfo<>(solutionService.querySolutionForPc(solutionType, sysAttr, buildingType,
                    null, 1, 1, 1, 1, SolutionStateEnum.SHELVE
                            .getDbValue(),
                    null, null, null
            ));
        }
        SolutionResp resp = BeanUtils.transfrom(SolutionResp.class, queryResult);
        List<SolutionResponseBean> solutionRespBeans = new ArrayList<>();
        resp.setList(solutionRespBeans);
        List<Solution> queryList = queryResult.getList();
        if (CollectionUtils.isNotEmpty(queryList)) {
            //用户收藏set
            HashSet<Long> collectSet = new HashSet<Long>();
            getCollectIds(uid, collectSet);
            List<Solution> hotList = hotResult.getList();
            SolutionResponseBean solutionResponse;
            for (Solution solution : queryList) {
                solutionResponse = new SolutionResponseBean();
                SolutionBeansConvertUtil.convert(solution, solutionResponse);
                if (CollectionUtils.isNotEmpty(hotList)) {
                    for (Solution hotSolution : hotList) {
                        if (hotSolution.getSolutionId().equals(solution.getSolutionId())) {
                            solutionResponse.setIsHot(true);
                            break;
                        }
                    }
                }

                solutionResponse.setIsCollect(collectSet.contains(solution.getSolutionId()) ? 1 : 0);
                if (uid != null) {
                    solutionResponse.setIsMy(solution.getUserId().intValue() == uid.intValue() ? 1 : 0);
                } else {
                    solutionResponse.setIsMy(0);
                }
                //增加品牌信息
                if (NumberHelper.validatePositive(solution.getBrandId())) {
                    BrandOwner brandOwner = brandOwnerService.getBrandOwnerById(solution.getBrandId());
                    if (brandOwner != null) {
                        solutionResponse.setBrandIocn(brandOwner.getBrandIcon());
                    }
                }
                //判断是否是品牌厂商
                if (NumberHelper.validatePositive(solution.getUserId())) {
                    BrandFirm brandFirm = brandFirmService.getBrandFirmByUserId(solution.getUserId());
                    if (brandFirm != null && SolutionStateEnum.AUDITSUCCESS.getDbValue() == brandFirm.getStatus()
                            .intValue()) {
                        solutionResponse.setFirmName(brandFirm.getFirmName());
                    }
                }
                solutionRespBeans.add(solutionResponse);
            }
        }
        return resp;
    }


    /**
     * @param solutionType 方案类型1:系统方案 2:品牌方案
     * @param keyword 搜索关键字
     * @param uid 当前登录用户
     * @param pageNum 当前页码
     * @param pageSize 每页记录数
     */
    public SolutionResp keyword(String solutionType, String keyword, Integer uid, Integer pageNum, Integer pageSize) {
        PageBean pageBean = new PageBean(pageNum, pageSize);
        String type = "1,2,3";
        if (solutionType != null) {
            if (!ArrayUtils.contains(new String[]{"1", "2"}, solutionType)) {
                throw new BizException(Meta.CODE_451.getCode(), "方案类型参数不合法!");
            }
            if (solutionType.equals("2")) {
                type = "2";
            } else {
                type = "1,3";
            }
        }
        List<SolutionResponseBean> responseList = new ArrayList<>();
        SearchResponseBean<SearchSolution> queryResult = searchService.querySolutionFromSearch(type, keyword, pageBean);
        List<SearchSolution> searchSolutionList = queryResult.getDocs();
        long total = queryResult.getTotal();
        if (NumberHelper.validatePositive(total)) {
            //用户收藏set
            HashSet<Long> collectSet = new HashSet<Long>();
            getCollectIds(uid, collectSet);
            SolutionResponseBean solutionResponse;
            for (SearchSolution searchSolution : searchSolutionList) {
                solutionResponse = new SolutionResponseBean();
                Solution solution = solutionService.findBySolutionId(searchSolution.getSolutionId());
                if (solution != null) {
                    SolutionBeansConvertUtil.convert(solution, solutionResponse);
                    if (uid != null) {
                        solutionResponse.setIsMy(solution.getUserId().intValue() == uid.intValue() ? 1 : 0);
                    } else {
                        solutionResponse.setIsMy(0);
                    }
                    solutionResponse.setIsCollect(collectSet.contains(searchSolution.getSolutionId()) ? 1 : 0);
                    responseList.add(solutionResponse);
                    //增加品牌信息
                    if (NumberHelper.validatePositive(solution.getBrandId())) {
                        BrandOwner brandOwner = brandOwnerService.getBrandOwnerById(solution.getBrandId());
                        if (brandOwner != null) {
                            solutionResponse.setBrandIocn(brandOwner.getBrandIcon());
                        }
                    }
                    //判断是否是品牌厂商
                    if (NumberHelper.validatePositive(solution.getUserId())) {
                        BrandFirm brandFirm = brandFirmService.getBrandFirmByUserId(solution.getUserId());
                        if (brandFirm != null && SolutionStateEnum.AUDITSUCCESS.getDbValue() == brandFirm.getStatus()
                                .intValue()) {
                            solutionResponse.setFirmName(brandFirm.getFirmName());
                        }
                    }
                }
            }
        }
        return new SolutionResp(responseList, pageBean.getCurrentPage(),
                pageBean.getPageSize(), total);
    }

    private void getCollectIds(Integer uid, HashSet<Long> collectSet) {
        if (NumberHelper.validatePositive(uid)) {
            //获取该用户的收藏列表
            List<UserSolution> userSolutionList = userSolutionService.getUserSolutionList(uid,
                    DownloadCollectEnum.COLLECTION.getDbValue());
            if (CollectionUtils.isNotEmpty(userSolutionList)) {
                for (UserSolution userSolution : userSolutionList) {
                    collectSet.add(userSolution.getSolutionId());
                }
            }
        }
    }

    public SolutionResp queryFreeSolution4Home(Integer isFree, Integer pageNum, Integer pageSize) {
        if (isFree != null) {
            if (!ArrayUtils.contains(new Integer[]{0, 1}, isFree)) {
                throw new BizException(Meta.CODE_451.getCode(), "isFree类型不正确");
            }
        }
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<Solution> pageInfo = new PageInfo<>(solutionService.queryFreeSolution4Home(isFree));
        SolutionResp resp = BeanUtils.transfrom(SolutionResp.class, pageInfo);
        resp.setList(BeanUtils.batchTransform(SolutionResponseBean.class, pageInfo.getList()));
        return resp;
    }

    public BrandFirmSolutionResp queryBrandFirmSolution(Integer uid, Integer loginUserId, Integer pageNum,
            Integer pageSize) {
        if (!NumberHelper.validatePositive(uid)) {
            throw new BizException(Meta.CODE_451.getCode(), "uid格式错误");
        }
        List<BrandFirmSolutionResponseBean> responseList = new ArrayList<BrandFirmSolutionResponseBean>();
        PageInfo<Solution> queryResult = null;
        PageHelper.startPage(pageNum, pageSize);
        if (NumberHelper.validatePositive(loginUserId) && uid.equals(loginUserId)) {
            queryResult = new PageInfo<>(solutionService.queryBrandFirmSolution2(loginUserId));
        } else {
            queryResult = new PageInfo<>(solutionService.queryBrandFirmSolution(uid));
        }
        List<Solution> queryList = queryResult.getList();
        BrandFirm brandFirm = brandFirmService.getBrandFirmByUserId(uid);
        if (brandFirm == null || brandFirm.getStatus().intValue() != SolutionStateEnum.AUDITSUCCESS.getDbValue()) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "该品牌厂商不存在!");
        }
        BrandOwner brandOwner = brandOwnerService.getBrandOwnerById(brandFirm.getBrandId());
        if (brandOwner == null) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "关联品牌主不存在!");
        }
        if (CollectionUtils.isNotEmpty(queryList)) {
            for (Solution solution : queryList) {
                BrandFirmSolutionResponseBean solutionResponse = BeanUtils
                        .transfrom(BrandFirmSolutionResponseBean.class, solution);
                solutionResponse.setFirmName(brandFirm.getFirmName());
                solutionResponse.setBrandIcon(brandOwner.getBrandIcon());
                responseList.add(solutionResponse);
            }
        }
        BrandFirmSolutionResp resp = BeanUtils.transfrom(BrandFirmSolutionResp.class, queryResult);
        resp.setList(responseList);
        return resp;
    }

    public UserDownloadAuthResp auth(Integer uid, Long solutionId) {
        if (!NumberHelper.validatePositive(uid) || !NumberHelper.validatePositive(solutionId)) {
            throw new BizException(Meta.CODE_451.getCode(), "参数不合法！");
        }
        Solution solution = solutionService.findBySolutionId(solutionId);
        if (solution == null) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "该方案不存在!");
        }
        if (solution.getIsAdmitDownload() == 0) {
            throw new BizException(ErrorCodeEnum.NotSupport.getDbValue(), "该方案不允许下载！");
        }

        UserDownloadAuthResp downloadAuth = new UserDownloadAuthResp();
        downloadAuth.setSolutionId(solution.getSolutionId());
        downloadAuth.setSolutionName(solution.getSolutionName());
        downloadAuth.setAttachment(null);
        downloadAuth.setIsAllowDownload(0);
        //当前用户为该方案的上传者，可以下载
        if (solution.getUserId().equals(uid) || solution.getExpertId().equals(uid)) {
            // 表示当前有权限下载
            downloadAuth.setIsAllowDownload(1);
            downloadAuth.setAttachment(solution.getAttachment());
        } else {
            if (solution.getIsFree().intValue() == 0) {
                // 表示当前有权限下载
                downloadAuth.setIsAllowDownload(1);
                downloadAuth.setAttachment(solution.getAttachment());
            } else {
                UserPayOrder order = userPayOrderService.queryUserPayOrder(solutionId, uid);
                if (order != null && order.getStatus().intValue() == PayStateEnum.PAYCOMPLETE.getDbValue()) {
                    // 表示当前有权限下载
                    downloadAuth.setIsAllowDownload(1);
                    downloadAuth.setAttachment(solution.getAttachment());
                }
            }
        }
        return downloadAuth;
    }

    public UserSolutionResp userSolList(Integer userId, String solutionName, Integer status, Integer isAdmitDownload,
            Integer isFree, Integer expType, Integer pageNum, Integer pageSize) {
        if (!NumberHelper.validatePositive(userId)) {
            throw new BizException(Meta.CODE_451.getCode(), "userId不合规");
        }
        List<UserSolutionBean> responseList = new ArrayList<>();
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<Solution> queryResult = new PageInfo<>(
                solutionService.queryUserSolutionList(userId, solutionName, status, isAdmitDownload, isFree, expType));
        List<Solution> queryList = queryResult.getList();
        if (CollectionUtils.isNotEmpty(queryList)) {
            for (Solution solution : queryList) {
                UserSolutionBean solutionResponse = BeanUtils.transfrom(UserSolutionBean.class, solution);
                solutionResponse.setStatusStr(SolutionStateEnum.getExistDisplayValue(solution.getStatus()));
                Integer hebiTotal = hebiOrderService.queryHebiByBusinessId(solution.getSolutionId().toString());
                solutionResponse.setHebiTotal(hebiTotal);
                List<UserPayOrder> list = userPayOrderService
                        .queryOrderByBusinessId(solution.getSolutionId(), BusinessTypeEnum.SOLUTION.getDbValue(),
                                PayStateEnum.PAYCOMPLETE.getDbValue());
                if (CollectionUtils.isNotEmpty(list)) {
                    solutionResponse.setPayCount(list.size());
                } else {
                    solutionResponse.setPayCount(0);
                }
                responseList.add(solutionResponse);
            }
        }
        UserSolutionResp resp = BeanUtils.transfrom(UserSolutionResp.class, queryResult);
        resp.setList(responseList);
        return resp;
    }

    public UserSolutionDetailResp earning(Long solutionId) {
        if (!NumberHelper.validatePositive(solutionId)) {
            throw new BizException(Meta.CODE_451.getCode(), "solutionId格式有误！");
        }
        Solution solution = solutionService.findBySolutionId(solutionId);
        if (solution == null) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "方案不存在！");
        }
        UserSolutionDetailResp solutionDetailResponse = BeanUtils.transfrom(UserSolutionDetailResp.class, solution);
        solutionDetailResponse.setStatusStr(SolutionStateEnum.getExistDisplayValue(solution.getStatus()));
        solutionDetailResponse.setPayCount(0);
        //总收入
        BigDecimal totalAmount = new BigDecimal(0);
        List<UserPayOrder> list = userPayOrderService
                .queryOrderByBusinessId(solutionId, BusinessTypeEnum.SOLUTION.getDbValue(),
                        PayStateEnum.PAYCOMPLETE.getDbValue());
        if (CollectionUtils.isNotEmpty(list)) {
            List<UserIncomeDetailResponseBean> downloadList = new ArrayList<UserIncomeDetailResponseBean>();
            UserIncomeDetailResponseBean download;
            for (UserPayOrder userPayOrder : list) {
                download = new UserIncomeDetailResponseBean();
                download.setBusinessId(userPayOrder.getBusinessId());
                download.setDownloadTime(userPayOrder.getLastModifiedTime());
                BigDecimal amount = userPayOrder.getAmount().multiply(new BigDecimal(0.5));
                download.setAmount(amount);
                downloadList.add(download);
                totalAmount = totalAmount.add(amount);
            }
            solutionDetailResponse.setPayCount(list.size());
            solutionDetailResponse.setTotalAmount(totalAmount);
            solutionDetailResponse.setList(downloadList);
        }
        return solutionDetailResponse;
    }

    public SolutionListResp hotList(Integer type, Integer number) {
        if (!ArrayUtils.contains(new int[]{1, 2, 3}, type)) {
            throw new BizException(Meta.CODE_451.getCode(), "type类型不正确");
        }
        if (number == null || number <= 0) {
            throw new BizException(Meta.CODE_451.getCode(), "number不合法");
        }
        PageHelper.startPage(1, number);
        PageInfo<SolutionListResponseBean> beanPageInfo = new PageInfo<>(
                solutionService.queryHotSolutionList(type, null));
        return BeanUtils.transfrom(SolutionListResp.class, beanPageInfo);
    }

    public SSolutionDetailResp detail(Long solutionId, Integer userId, Integer memberLevel) {
        Solution solution = solutionService.findBySolutionId(solutionId);
        if (solution == null) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "该方案不存在!");
        }

        if (!NumberHelper.validatePositive(userId)) {
            if (solution.getStatus().equals(SolutionStateEnum.UNSHELVE.getDbValue())) {
                throw new BizException(ErrorCodeEnum.NotSupport.getDbValue(), "该方案已下架!");
            }
        } else if (!solution.getUserId().equals(userId) && !solution.getExpertId().equals(userId)) {
            if (solution.getStatus().equals(SolutionStateEnum.UNSHELVE.getDbValue())) {
                throw new BizException(ErrorCodeEnum.NotSupport.getDbValue(), "该方案已下架!");
            }
        }

        SSolutionDetailResp solutionDetail = SolutionBeansConvertUtil.convert(solution);
        if (solutionDetail == null) {
            throw new BizException(ErrorCodeEnum.NotSupport.getDbValue(), "信息无法转换");
        }
        solutionDetail.setUserIsDownload(false);
        if (NumberHelper.validatePositive(userId)) {
            UserSolution userSolution = userSolutionService
                    .getUserSolution(userId, solution.getSolutionId(), DownloadCollectEnum.COLLECTION.getDbValue());
            //是否收藏 0:未收藏 1:已收藏
            solutionDetail.setIsCollect((userSolution == null || userSolution.getCollectionStatus() == 1) ? 0 : 1);
            //是否是我的方案
            solutionDetail.setIsMy(solution.getUserId().intValue() == userId.intValue() ? 1 : 0);
            //判断是否已经完成支付
            UserPayOrder userPayOrder = userPayOrderService.queryUserPayOrder(solutionId, userId);
            if (userPayOrder != null) {
                solutionDetail.setOrderNo(userPayOrder.getOrderNo());
                solutionDetail.setPayStatus(userPayOrder.getStatus());
            }
            //判断当前用户是否可以下载
            if (solution.getIsAdmitDownload().intValue() == DownloadEnum.CAN_DOWNLOAD.getDbValue()) {
                //允许下载
                if (solution.getIsFree().intValue() == ChargeEnum.UNCHARGE.getDbValue()) {
                    //免费下载方案
                    //查询当前用户当天免费方案下载次数
                    Integer downloadCount = userPayOrderService
                            .queryFreeSolutionDownloadCount(userId, DownloadCollectEnum.DOWNLOAD.getDbValue());
                    if (NumberHelper.validatePositive(memberLevel)) {
                        if (MemberLevelEnum.VIP_LEVEL_1.getDbValue().equals(memberLevel) || MemberLevelEnum.VIP_LEVEL_2
                                .getDbValue().equals(memberLevel)) {
                            if (10 > downloadCount.intValue()) {
                                solutionDetail.setUserIsDownload(true);
                            }
                        } else if (MemberLevelEnum.VIP_LEVEL_3.getDbValue().equals(memberLevel)
                                || MemberLevelEnum.VIP_LEVEL_4.getDbValue().equals(memberLevel)) {
                            if (15 > downloadCount.intValue()) {
                                solutionDetail.setUserIsDownload(true);
                            }
                        } else if (MemberLevelEnum.VIP_LEVEL_5.getDbValue().equals(memberLevel)
                                || MemberLevelEnum.VIP_LEVEL_6.getDbValue().equals(memberLevel)) {
                            if (20 > downloadCount.intValue()) {
                                solutionDetail.setUserIsDownload(true);
                            }
                        }
                    } else {
                        //非会员只能免费下载三次
                        if (3 > downloadCount.intValue()) {
                            solutionDetail.setUserIsDownload(true);
                        }
                    }
                } else {
                    //付费方案
                    if (userPayOrder != null && userPayOrder.getStatus().intValue() == PayStateEnum.PAYCOMPLETE
                            .getDbValue()) {
                        //完成付款
                        solutionDetail.setUserIsDownload(true);
                    }
                }
            }

        }
        //是否是专家方案
//			solutionDetail.setIsExpert(false);
//			if(NumberHelper.validatePositive(SOLUTION.getUserId())){
//				ExpertProfile expert = expertService.getExpert(SOLUTION.getUserId());
//				if(expert != null){
//					solutionDetail.setIsExpert(true);
//				}
//			}
//			if(NumberHelper.validatePositive(SOLUTION.getExpertId())){
//				ExpertProfile expert = expertService.getExpert(SOLUTION.getExpertId());
//				if(expert != null){
//					solutionDetail.setIsExpert(true);
//				}
//			}
        //增加品牌信息
        if (NumberHelper.validatePositive(solution.getBrandId())) {
            BrandOwner brandOwner = brandOwnerService.getBrandOwnerById(solution.getBrandId());
            if (brandOwner != null) {
                solutionDetail.setBrand(brandOwner.getBrandName());
                solutionDetail.setBrandIocn(brandOwner.getBrandIcon());
            }
        }
        //判断是否是品牌厂商
        if (NumberHelper.validatePositive(solution.getUserId())) {
            BrandFirm brandFirm = brandFirmService.getBrandFirmByUserId(solution.getUserId());
            if (brandFirm != null && SolutionStateEnum.AUDITSUCCESS.getDbValue() == brandFirm.getStatus().intValue()) {
                solutionDetail.setFirmName(brandFirm.getFirmName());
            }
        }
        //是否在活动时间范围
//			ActivityConfig activityConfig = activityConfigService.getActivityConfig(ActivityTypeEnum.ONE_YUAN_DOWNLOAD.getDbValue());
//			Date beginDate = activityConfig.getBeginTime();
//			Date endDate = activityConfig.getEndTime();
//			Date nowDate = new Date();
//			if(DateFormatter.getDiffDay(beginDate, nowDate) < 0 || DateFormatter.getDiffDay(endDate, nowDate) > 0){
//				solutionDetail.setActivitySolution(false);
//			}
        //增加附件转图片字段
        List<AttachmentInfoResponseBean> attachmentInfoList = new ArrayList<AttachmentInfoResponseBean>();
        List<Attachment> list = attachmentService
                .queryAttachmentByBusinessId(solution.getSolutionId(), BusinessTypeEnum.SOLUTION.getDbValue());
        AttachmentInfoResponseBean attachmentInfo;
        for (Attachment attachment : list) {
            attachmentInfo = new AttachmentInfoResponseBean();
            attachmentInfo.setId(attachment.getId());
            attachmentInfo.setBusinessId(attachment.getBusinessId());
            attachmentInfo.setBusinessType(attachment.getBusinessType());
            attachmentInfo.setAttachmentUrl(attachment.getAttachmentUrl());
            attachmentInfo.setAttachmentPicture(attachment.getAttachmentPicture());
            attachmentInfo.setCreateTime(attachment.getCreateTime());
            attachmentInfoList.add(attachmentInfo);
        }
        solutionDetail.setAttachmentInfoList(attachmentInfoList);
        //浏览数+1
        solutionService.addSolutionPageView(solution.getSolutionId());
        //发短信
        smsServiceImpl.sendVisitSolutionSMS(solution);
        return solutionDetail;
    }

    public USolutionDetailResp basicDetail(Integer userId, Long solutionId) {
        if (!NumberHelper.validatePositive(solutionId) ||
                !NumberHelper.validatePositive(userId)) {
            throw new BizException(Meta.CODE_451.getCode(), "参数有误！");
        }
        Solution solution = solutionService.findBySolutionId(solutionId);
        if (solution == null) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "该方案不存在!");
        }
        if (solution.getUserId().intValue() != userId.intValue()) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "当前用户不是该方案上传用户");
        }
        return BeanUtils.transfrom(USolutionDetailResp.class, solution);
    }

    public SkuListResp productSkus(Long solutionId) {
        if (!NumberHelper.validatePositive(solutionId)) {
            throw new BizException(Meta.CODE_451.getCode(), "solutionId不合规");
        }
        Solution solution = solutionService.findBySolutionId(solutionId);
        if (solution == null) {
            throw new BizException(ErrorCodeEnum.NotExist.getDbValue(), "该方案不存在!");
        }
        List<SolutionSku> listSolutionSku = solutionSkuService
                .listSolutionSkuForPc(solutionId, DeleteEnum.NOT_DEL.getDbValue());
        List<SkuListResponseBean> responseList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(listSolutionSku)) {
            String productIds = "";
            Collections.shuffle(listSolutionSku);
            if (listSolutionSku.size() == 1) {
                productIds = listSolutionSku.get(0).getSkuId();
            } else if (listSolutionSku.size() == 2) {
                productIds = listSolutionSku.get(0).getSkuId() + "," + listSolutionSku.get(1).getSkuId();
            } else if (listSolutionSku.size() >= 3) {
                productIds = listSolutionSku.get(0).getSkuId() + "," + listSolutionSku.get(1).getSkuId() + ","
                        + listSolutionSku.get(2).getSkuId();
            }

            responseList = homedoService.getSkusZB(productIds);
        }
        //过滤productName为空字符串的
        responseList  = responseList.stream()
            .filter(skuListResponseBean -> !"".equals(skuListResponseBean.getProductName()))
            .collect(Collectors.toList());

        SkuListResp resp = new SkuListResp();
        resp.setList(responseList);
        return resp;
    }

    public void add(SolutionAddPcReq solutionAddBean) {
        if (!SolutionBeansConvertUtil.validate(solutionAddBean)) {
            throw new BizException(Meta.CODE_451.getCode(), "参数有误！");
        }
        String buildType = solutionAddBean.getBuildingType();//建筑业态
        HashMap<String, String> jzytMap = commonTypeDataService.getDataById(CommonTypeDataEnum.JZYT.getDbValue());

        if (!CommonDataUtil.validate(buildType, jzytMap)) {
            throw new BizException(Meta.CODE_451.getCode(), "建筑业态选项不合法!");
        }

        Integer firstSysAttr = solutionAddBean.getFirstSysAttr();//一级系统属性
        HashMap<String, String> yjxtsxMap = commonTypeDataService.getDataById(CommonTypeDataEnum.YJXTSX.getDbValue());
        if (!CommonDataUtil.validate(String.valueOf(firstSysAttr), yjxtsxMap)) {
            throw new BizException(Meta.CODE_451.getCode(), "一级系统属性选项不合法!");
        }
        String secondSysTag = solutionAddBean.getSecondSysAttr();//二级系统属性
        if (!CommonDataUtil.validate(secondSysTag, yjxtsxMap)) {
            throw new BizException(Meta.CODE_451.getCode(), "二级系统属性选项不合法!");
        }
        Solution solution = new Solution();
        SolutionBeansConvertUtil.convert(solution, solutionAddBean);
        //判断当前用户是否是品牌商用户
        BrandFirm brandFirm = brandFirmService.getBrandFirmByUserId(solutionAddBean.getUserId());
        //判断当前用户是否为专家用户
//        ExpertProfile expert = expertService.getExpert(solutionAddBean.getUserId());
        if (null != brandFirm && SolutionStateEnum.AUDITSUCCESS.getDbValue() == brandFirm.getStatus().intValue()) {
            //方案类型为品牌用户上传
            solution.setSolutionType(SolutionTypeEnum.BRAND_SOLUTION.getDbValue());
            BrandOwner brandOwner = brandOwnerService.getBrandOwnerById(brandFirm.getBrandId());
            if (brandOwner != null) {
                solution.setBrandId(brandOwner.getId());
            }
        /*}else if(null != expert){
            //方案类型为专家上传
            SOLUTION.setExpertId(solutionAddBean.getUserId());
            SOLUTION.setExpertName(solutionAddBean.getUserName());
            SOLUTION.setSolutionType(SolutionTypeEnum.EXPERT_SOLUTION.getDbValue());*/
        } else {
            //方案类型为用户上传
            solution.setSolutionType(SolutionTypeEnum.USER_UPLOAD_SOLUTION.getDbValue());
        }
        //状态未待审核
        solution.setStatus(SolutionStateEnum.BACKAUDIT.getDbValue());
        solution.setCreateTime(new Date());
        solution.setFormType(FromTypeEnum.FRONT_UPLOAD.getDbValue());
        Long solutionId = solutionService.addSolution(solution);
        //增加方案附件详细信息
        String attachment = solution.getAttachment();
        addAttachment(solution, attachment);
    }

    public void edit(SolutionEditPcReq solutionEditBean) {
        Solution solution = solutionService.findBySolutionId(Long.parseLong(solutionEditBean.getSolutionId()));
        if (solution == null) {
            throw new BizException(Meta.CODE_451.getCode(), "该方案不存在！");
        }
        if (solutionEditBean.getUserId().intValue() != solution.getUserId().intValue()) {
            throw new BizException(Meta.CODE_451.getCode(), "当前编辑用户不是该方案上传用户!");
        }
        //状态为待专家审核以及已上架时 不允许编辑
        Integer solutionStatus = solution.getStatus();
        if (ArrayUtils.contains(
                new int[]{SolutionStateEnum.PENDINGAUDIT.getDbValue(), SolutionStateEnum.BACKAUDIT.getDbValue(),
                        SolutionStateEnum.SHELVE.getDbValue()}, solutionStatus)) {
            throw new BizException(ErrorCodeEnum.NotSupport.getDbValue(), "状态为待专家审核以及已上架时 不允许编辑");
        }
        SolutionBeansConvertUtil.convert(solutionEditBean, solution);
        Integer firstSysAttr = solution.getFirstSysAttr();//一级系统属性
        HashMap<String, String> yjxtsxMap = commonTypeDataService.getDataById(CommonTypeDataEnum.YJXTSX.getDbValue());
        if (!CommonDataUtil.validate(String.valueOf(firstSysAttr), yjxtsxMap)) {
            throw new BizException(Meta.CODE_451.getCode(), "一级系统属性选项不合法!");
        }

        String secondSysTag = solution.getSecondSysAttr();//二级系统属性
        if (!CommonDataUtil.validate(secondSysTag, yjxtsxMap)) {
            throw new BizException(Meta.CODE_451.getCode(), "二级系统属性选项不合法!");
        }
        solution.setLastModifiedTime(new Date());
        //状态修改为待审核
        solution.setStatus(SolutionStateEnum.BACKAUDIT.getDbValue());
        solutionService.editSolution(solution);
        //先删除原有方案附件
        attachmentService.delAttachmentByBusinessId(solution.getSolutionId(), BusinessTypeEnum.SOLUTION.getDbValue());
        //增加方案附件详细信息
        String attachment = solution.getAttachment();
        addAttachment(solution, attachment);
    }

    /**
     * 新增附件信息
     */
    private void addAttachment(Solution solution, String attachment) {
        attachmentService.addAttachment(attachment, solution.getSolutionId(), BusinessTypeEnum.SOLUTION.getDbValue());
    }
}
